#include "grpceventserverservice.h"
#include "grpcclientproxyinserver.h"

#include "grpceventdispatchercore.h"
#include <QDebug>

std::shared_ptr<GrpcEventServerService> g_pEventService = nullptr;
GrpcEventServerService::GrpcEventServerService()
{

}

void GrpcEventServerService::SendEvent(const std::string &client, const std::string &jsonText)
{
    std::lock_guard<std::mutex> lk(m_mutex);
    if(m_clients.end() != m_clients.find(client))
    {
        m_clients[client]->SendEvent(jsonText);
    }
    else
    {
        qCritical() << "Not find client name = " << client.c_str();
    }
}

void GrpcEventServerService::ClientEndFlow(std::string name)
{
    std::lock_guard<std::mutex> lk(m_mutex);
    //这里只是删除map.而不delete, 因为delete 只应该在Reactor 内部的 onDone 处理
    m_clients.erase(name);
}

grpc::ServerUnaryReactor* GrpcEventServerService::Dispatch(CallbackServerContext* context,
        const GrpcEventMessage* request, GrpcEventMessage* response)
{
    //分发事件
    g_pEventDispatcher->DispatchLocal(request->jsontext());

    auto* reactor = context->DefaultReactor();
    reactor->Finish(Status::OK);
    return reactor;
}

grpc::ServerWriteReactor<GrpcEventMessage>* GrpcEventServerService::SubscribeDispatch(
    CallbackServerContext* context, const GrpcEventMessage* request)
{

    std::string name = request->jsontext();//启动流发的字符串就是客户端名称
    qDebug() << "SubscribeDispatch " << name.c_str();


    std::lock_guard<std::mutex> lk(m_mutex);
    if(m_clients.end() != m_clients.find(name))
    {
        //冲突了，不能
        qCritical() << "new client connect but name conflict, new null proxy";
        //context->TryCancel();
//        auto proxy = new GrpcClientProxyInService("", this);
//        proxy->Finish(Status::CANCELLED);
//        return proxy;

        delete m_clients[name];
    }
    m_clients[name] = new GrpcClientProxyInService(name, this);


    return m_clients[name];
}
